package com.team.auth.config.security;

import com.team.auth.config.exception.SsoException;
import com.team.auth.config.exception.SsoExceptionEnums;
import com.team.auth.entity.OauthClientDetails;
import com.team.auth.service.OauthClientDetailsService;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.security.crypto.password.PasswordEncoder;
import org.springframework.security.oauth2.provider.ClientDetails;
import org.springframework.security.oauth2.provider.ClientDetailsService;
import org.springframework.security.oauth2.provider.ClientRegistrationException;
import org.springframework.security.oauth2.provider.client.BaseClientDetails;
import org.springframework.stereotype.Service;

import java.util.Arrays;
import java.util.HashSet;


@Service
public class CustomizeClientDetailService implements ClientDetailsService {
    @Autowired
    private OauthClientDetailsService oauthClientDetailsService;
    @Autowired
    private PasswordEncoder customizePasswordEncoder;

    @Override
    public ClientDetails loadClientByClientId(String clientId) throws ClientRegistrationException {
        OauthClientDetails model = oauthClientDetailsService.selectById(clientId);
        if (model == null){
            throw new SsoException(SsoExceptionEnums.CLIENT_NOT_EXIST);
        }
        BaseClientDetails clientDetails = new BaseClientDetails();
        clientDetails.setClientId(model.getClientId()); //客户端(client)id
        clientDetails.setResourceIds(Arrays.asList(model.getResourceIds().split(",")));//客户端所能访问的资源id集合
        clientDetails.setClientSecret(customizePasswordEncoder.encode(model.getClientSecret()));//客户端(client)的访问密匙
        clientDetails.setAuthorizedGrantTypes(Arrays.asList(model.getAuthorizedGrantTypes().split(",")));//客户端支持的grant_type授权类型
        clientDetails.setScope(Arrays.asList(model.getScope().split(",")));//客户端申请的权限范围
        HashSet<String> redirectUri = new HashSet<>();
        redirectUri.add(model.getWebServerRedirectUri());
        clientDetails.setRegisteredRedirectUri(redirectUri);
        Integer accessTokenValidity = model.getAccessTokenValidity();
        if (accessTokenValidity != null && accessTokenValidity > 0) {
            clientDetails.setAccessTokenValiditySeconds(accessTokenValidity);//设置token的有效期，不设置默认12小时
        }
        Integer refreshTokenValidity = model.getRefreshTokenValidity();
        if (refreshTokenValidity != null && refreshTokenValidity > 0) {
            clientDetails.setRefreshTokenValiditySeconds(refreshTokenValidity);//设置刷新token的有效期，不设置默认30天
        }
        return clientDetails;
    }
}
